package com.luych.toolbox.common.service.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class HttpException extends RuntimeException {

    private static final Logger logger = LoggerFactory.getLogger(HttpException.class);

    private final ResponseEntity<String> responseEntity;

    public HttpException() {
        this.responseEntity = null;
    }

    public HttpException(HttpStatus code) {
        super(code.getReasonPhrase());
        this.responseEntity = new ResponseEntity<>(code.getReasonPhrase(), code);
    }

    public HttpException(HttpStatus code, String message) {
        super(message);
        this.responseEntity = new ResponseEntity<>(message, code);
    }

    public HttpException(HttpStatus code, String message, Throwable throwable) {
        super(message, throwable);
        this.responseEntity = new ResponseEntity<>(message, code);
    }

    public ResponseEntity<String> getResponseEntity() {
        return responseEntity;
    }

    @ExceptionHandler(HttpException.class)
    public ResponseEntity<String> onHttpException(HttpException e) {
        logger.info("Get HttpException: {}", e.getMessage());
        return e.getResponseEntity();
    }
}
